package com.csaba.connector.bha;

import java.util.ArrayList;

import com.csaba.connector.ServiceException;
import com.csaba.connector.bha.model.BHACurrentAccount;
import com.csaba.connector.bha.model.BHADepositAccount;
import com.csaba.connector.bha.model.BHALoanAccount;
import com.csaba.connector.bha.model.BHASession;
import com.csaba.connector.model.Account;
import com.csaba.connector.model.Customer;
import com.csaba.connector.model.Session;
import com.csaba.connector.service.AbstractAccountService;
import com.ind.simplenode.SimpleNode;

public class BHAAccountService extends AbstractAccountService
{

	@Override
	public void execute( final Session session ) throws ServiceException
	{
		final BHASession local = (BHASession) session;

		final SimpleNode request = new SimpleNode();
		final SimpleNode response = local.sendRequest("AccOverview", "getCustomerPortfolio", request, null);

		final ArrayList<Account> result = new ArrayList<Account>();

		final Customer customer = local.getCustomer();

		if ( response.exists("accounts") )
		{
			final SimpleNode[] accounts = response.getNodeArray("accounts");
			final String[] accountNames = response.getStringArray("accountNames");
			int i = 0;
			for ( final SimpleNode account : accounts )
			{
				final Account acc = new BHACurrentAccount(customer, account);
				if ( accountNames != null )
					acc.setName(accountNames[i]);
				i++;

				result.add(acc);
			}
		}

		if ( response.exists("deposits") )
		{
			final SimpleNode[] deposits = response.getNodeArray("deposits");
			for ( final SimpleNode deposit : deposits )
			{
				final Account acc = new BHADepositAccount(customer, deposit);

				result.add(acc);
			}
		}

		if ( response.exists("loans") )
		{ //TEST IT! This is not tested, as there is no loan account for the test account.
			//XXX perhaps implementing demo functionality as in the demo, would help.
			final SimpleNode[] deposits = response.getNodeArray("loans");
			for ( final SimpleNode deposit : deposits )
			{
				final Account acc = new BHALoanAccount(customer, deposit);

				result.add(acc);
			}
		}

		accounts = result.toArray(new Account[result.size()]);
	}
}
